<template>
  <div class="shop-management">

    <!-- 搜索区域 -->
    <div class="search-area">
      <el-card shadow="never">
        <el-form :model="searchForm" :inline="true" class="search-form">
          <!-- 第一行搜索条件 -->
          <el-form-item label="社区">
            <el-select 
              v-model="searchForm.communityId" 
              placeholder="请选择社区" 
              clearable
              style="width: 200px"
            >
              <el-option
                v-for="community in communityList"
                :key="community.id"
                :label="community.communityName"
                :value="community.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="店铺类型">
            <el-select 
              v-model="searchForm.shopType" 
              placeholder="请选择店铺类型" 
              clearable
              style="width: 150px"
            >
              <el-option label="餐饮" :value="1" />
              <el-option label="零售" :value="2" />
              <el-option label="服务" :value="3" />
              <el-option label="其他" :value="4" />
            </el-select>
          </el-form-item>
          <el-form-item label="店铺名称">
            <el-input 
              v-model="searchForm.shopName" 
              placeholder="请输入店铺名称" 
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="店铺编码">
            <el-input 
              v-model="searchForm.shopCode" 
              placeholder="请输入店铺编码" 
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="状态">
            <el-select 
              v-model="searchForm.status" 
              placeholder="请选择状态" 
              clearable
              style="width: 120px"
            >
              <el-option label="启用" :value="1" />
              <el-option label="禁用" :value="0" />
            </el-select>
          </el-form-item>
          
          <!-- 第二行搜索条件 -->
          <el-form-item label="房间号">
            <el-input 
              v-model="searchForm.roomNumber" 
              placeholder="请输入房间号" 
              clearable
              style="width: 150px"
            />
          </el-form-item>
          <el-form-item label="联系人">
            <el-input 
              v-model="searchForm.contactPerson" 
              placeholder="请输入联系人" 
              clearable
              style="width: 150px"
            />
          </el-form-item>
          <el-form-item label="联系电话">
            <el-input 
              v-model="searchForm.contactPhone" 
              placeholder="请输入联系电话" 
              clearable
              style="width: 180px"
            />
          </el-form-item>
          <el-form-item label="面积范围">
            <el-input 
              v-model="searchForm.minArea" 
              placeholder="最小面积" 
              clearable
              style="width: 100px"
            />
            <span style="margin: 0 8px">-</span>
            <el-input 
              v-model="searchForm.maxArea" 
              placeholder="最大面积" 
              clearable
              style="width: 100px"
            />
          </el-form-item>
          <el-form-item label="租金范围">
            <el-input 
              v-model="searchForm.minRentPrice" 
              placeholder="最小租金" 
              clearable
              style="width: 100px"
            />
            <span style="margin: 0 8px">-</span>
            <el-input 
              v-model="searchForm.maxRentPrice" 
              placeholder="最大租金" 
              clearable
              style="width: 100px"
            />
          </el-form-item>
          
          <!-- 搜索按钮 -->
          <el-form-item>
            <el-button type="primary" @click="handleSearch" :loading="loading">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 操作区域 -->
    <div class="operation-area">
      <el-card shadow="never">
        <div class="operation-buttons">
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增店铺
          </el-button>
          <el-button type="success" @click="handleExport" :disabled="shopList.length === 0">
            <el-icon><Download /></el-icon>
            导出数据
          </el-button>
          <el-button type="info" @click="handleRefresh">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </el-card>
    </div>

    <!-- 表格区域 -->
    <div class="table-area">
      <el-card shadow="never">
        <el-table 
          v-if="shopList.length >= 0"
          :data="shopList" 
          v-loading="loading"
          stripe
          border
          style="width: 100%"
          @selection-change="handleSelectionChange"
          :key="'shop-table-' + shopList.length + '-' + Date.now()"
        >
          <!-- 选择列 -->
          <el-table-column type="selection" width="55" :key="'selection'" />
          
          <!-- 店铺名称 -->
          <el-table-column prop="shopName" label="店铺名称" min-width="120" :key="'shopName'" />
          
          <!-- 店铺图片 -->
          <el-table-column label="店铺图片" width="100" :key="'shopImages'">
            <template #default="{ row }">
              <div class="shop-image-thumbnail">
                <el-image
                  v-if="row.firstImageUrl"
                  :src="row.firstImageUrl"
                  :preview-src-list="row.imageUrls || []"
                  fit="cover"
                  style="width: 60px; height: 40px; border-radius: 4px;"
                  :initial-index="0"
                />
                <div v-else class="no-image">
                  <el-icon><Picture /></el-icon>
                  <span>暂无图片</span>
                </div>
              </div>
            </template>
          </el-table-column>
          
          <!-- 店铺编码 -->
          <el-table-column prop="shopCode" label="店铺编码" width="120" :key="'shopCode'" />
          
          <!-- 店铺类型 -->
          <el-table-column prop="shopTypeName" label="店铺类型" width="100" :key="'shopType'">
            <template #default="{ row }">
              <el-tag :type="getShopTypeTagType(row.shopType)">
                {{ row.shopTypeName }}
              </el-tag>
            </template>
          </el-table-column>
          
          <!-- 所属社区 -->
          <el-table-column prop="communityName" label="所属社区" min-width="120" :key="'communityName'" />
          
          <!-- 所属楼栋 -->
          <el-table-column prop="buildingName" label="所属楼栋" min-width="100" :key="'buildingName'" />
          
          <!-- 房间号 -->
          <el-table-column prop="roomNumber" label="房间号" width="100" :key="'roomNumber'" />
          
          <!-- 面积 -->
          <el-table-column prop="area" label="面积(㎡)" width="100" :key="'area'">
            <template #default="{ row }">
              {{ row.area && typeof row.area === 'number' ? row.area.toFixed(2) : (row.area || '-') }}
            </template>
          </el-table-column>
          
          <!-- 租金 -->
          <el-table-column prop="rentPrice" label="租金(元)" width="120" :key="'rentPrice'">
            <template #default="{ row }">
              <span class="money-text">{{ row.rentPrice && typeof row.rentPrice === 'number' ? '¥' + row.rentPrice.toFixed(2) : (row.rentPrice ? '¥' + row.rentPrice : '-') }}</span>
            </template>
          </el-table-column>
          
          <!-- 联系人 -->
          <el-table-column prop="contactPerson" label="联系人" width="100" :key="'contactPerson'">
            <template #default="{ row }">
              {{ row.contactPerson || '-' }}
            </template>
          </el-table-column>
          
          <!-- 状态 -->
          <el-table-column prop="statusName" label="状态" width="80" :key="'status'">
            <template #default="{ row }">
              <el-tag :type="row.status === 1 ? 'success' : 'danger'">
                {{ row.statusName }}
              </el-tag>
            </template>
          </el-table-column>
          
          <!-- 创建时间 -->
          <el-table-column prop="createTime" label="创建时间" width="160" :key="'createTime'">
            <template #default="{ row }">
              {{ formatDateTime(row.createTime) }}
            </template>
          </el-table-column>
          
          <!-- 操作 -->
          <el-table-column label="操作" width="200" fixed="right" :key="'operation'">
            <template #default="{ row }">
              <el-button type="primary" size="small" @click="handleView(row)">
                <el-icon><View /></el-icon>
                查看
              </el-button>
              <el-button type="warning" size="small" @click="handleEdit(row)">
                <el-icon><Edit /></el-icon>
                编辑
              </el-button>
              <el-button type="danger" size="small" @click="handleDelete(row)">
                <el-icon><Delete /></el-icon>
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>

    <!-- 分页区域 -->
    <div class="pagination-area">
      <el-card shadow="never">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-card>
    </div>

    <!-- 店铺详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="店铺详情"
      width="800px"
      :close-on-click-modal="false"
    >
      <ShopDetail v-if="detailDialogVisible" :shop-id="selectedShopId" :model-value="detailDialogVisible" @update:model-value="detailDialogVisible = $event" />
    </el-dialog>

    <!-- 店铺表单对话框 -->
    <el-dialog
      v-model="formDialogVisible"
      :title="formTitle"
      width="600px"
      :close-on-click-modal="false"
    >
      <ShopForm 
        v-if="formDialogVisible" 
        :shop-id="selectedShopId"
        :mode="formMode"
        @success="handleFormSuccess"
        @cancel="handleFormCancel"
      />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Search, 
  Refresh, 
  Plus, 
  Download, 
  View, 
  Edit, 
  Delete,
  Picture
} from '@element-plus/icons-vue'
import ShopForm from './components/ShopForm.vue'
import ShopDetail from './components/ShopDetail.vue'
import { shopApi } from '@/api/shop'
import { communityApi } from '@/api/community'
import api from '@/api/request'
import type { ShopDetail as ShopVO } from '@/api/shop'
import type { CommunityData as CommunityVO } from '@/api/community'

// 响应式数据
const loading = ref(false)
const shopList = ref<ShopVO[]>([])
const communityList = ref<CommunityVO[]>([])
const selectedRows = ref<ShopVO[]>([])

// 搜索表单
const searchForm = reactive({
  communityId: undefined as number | undefined,
  shopType: undefined as number | undefined,
  shopName: '',
  shopCode: '',
  roomNumber: '',
  contactPerson: '',
  contactPhone: '',
  status: undefined as number | undefined,
  minArea: undefined as number | undefined,
  maxArea: undefined as number | undefined,
  minRentPrice: undefined as number | undefined,
  maxRentPrice: undefined as number | undefined
})

// 分页信息
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 对话框状态
const detailDialogVisible = ref(false)
const formDialogVisible = ref(false)
const selectedShopId = ref<number | null>(null)
const formMode = ref<'add' | 'edit'>('add')

// 计算属性
const formTitle = computed(() => {
  return formMode.value === 'add' ? '新增店铺' : '编辑店铺'
})

// 生命周期
onMounted(() => {
  loadShopList()
  loadCommunityList()
})

// 方法
const loadShopList = async () => {
  loading.value = true
  try {
    const response = await shopApi.getShopPage({
      current: pagination.current,
      size: pagination.size,
      communityId: searchForm.communityId,
      shopType: searchForm.shopType,
      shopName: searchForm.shopName,
      shopCode: searchForm.shopCode,
      roomNumber: searchForm.roomNumber,
      contactPerson: searchForm.contactPerson,
      contactPhone: searchForm.contactPhone,
      status: searchForm.status,
      minArea: searchForm.minArea,
      maxArea: searchForm.maxArea,
      minRentPrice: searchForm.minRentPrice,
      maxRentPrice: searchForm.maxRentPrice
    })
    
    console.log('店铺列表响应:', response)
    
    // 检查响应结构是否正常
    if (response) {
      if (response.code === 200 && response.success === true) {
        // API调用成功，更新数据
        shopList.value = response.data?.records || []
        pagination.total = response.data?.total || 0
        console.log('店铺列表数据加载成功:', shopList.value)
        console.log('分页信息:', pagination.total)
        
        
        // 调试：检查数据结构
        if (shopList.value.length > 0) {
          console.log('第一条店铺数据:', shopList.value[0])
          console.log('状态字段:', shopList.value[0].status, shopList.value[0].statusName)
          console.log('租金字段:', shopList.value[0].rentPrice, typeof shopList.value[0].rentPrice)
          console.log('联系人字段:', shopList.value[0].contactPerson, typeof shopList.value[0].contactPerson)
          console.log('所有字段:', Object.keys(shopList.value[0]))
          console.log('表格列数:', document.querySelectorAll('.el-table__header th').length)
          
          // 详细检查每个字段的值
          const firstRow = shopList.value[0]
          console.log('=== 字段值详细检查 ===')
          console.log('id:', firstRow.id)
          console.log('shopName:', firstRow.shopName)
          console.log('shopCode:', firstRow.shopCode)
          console.log('shopType:', firstRow.shopType, 'shopTypeName:', firstRow.shopTypeName)
          console.log('communityName:', firstRow.communityName)
          console.log('buildingName:', firstRow.buildingName)
          console.log('roomNumber:', firstRow.roomNumber)
          console.log('area:', firstRow.area)
          console.log('rentPrice:', firstRow.rentPrice)
          console.log('contactPerson:', firstRow.contactPerson)
          console.log('status:', firstRow.status, 'statusName:', firstRow.statusName)
          console.log('createTime:', firstRow.createTime)
        }
        
        // 根据数据情况显示适当的提示
        if (shopList.value.length === 0) {
          // 数据为空，显示信息提示（蓝色）
          ElMessage.info('暂无店铺数据')
        } else {
          // 有数据，显示成功提示（绿色）
          ElMessage.success(response.message || '店铺列表加载成功')
        }
        
        // 确保DOM更新
        await nextTick()
        console.log('DOM更新完成，表格列数:', document.querySelectorAll('.el-table__header th').length)
      } else {
        // API返回业务错误
        const errorMessage = response.message || '加载店铺列表失败'
        console.error('API业务错误:', response.code, errorMessage)
        ElMessage.error(errorMessage)
      }
    } else {
      // 响应结构异常
      console.error('API响应结构异常:', response)
      ElMessage.error('加载店铺列表失败：响应数据格式异常')
    }
  } catch (error: any) {
    // 处理业务错误和网络错误
    if (error && error.isBusinessError) {
      // 业务错误，使用后端返回的错误消息
      const errorMessage = error.message || '加载店铺列表失败'
      console.error('API业务错误:', error.code, errorMessage)
      ElMessage.error(errorMessage)
    } else {
      // 网络错误或其他异常
      console.error('店铺列表加载异常:', error)
      ElMessage.error('加载店铺列表失败：网络连接异常')
    }
  } finally {
    loading.value = false
  }
}

const loadCommunityList = async () => {
  try {
    // 使用正确的社区API接口，遵循开发规范
    const response = await communityApi.getCommunityList({})
    console.log('社区列表响应:', response)
    
    // 检查API响应结构
    if (response.code === 200) {
      // 转换数据结构以匹配前端期望的格式
      const communities = response.data || []
      console.log('社区数据:', communities)
      
      communityList.value = communities.map((item: any) => ({
        id: item.id,
        communityName: item.communityName,
        communityCode: item.communityCode,
        regionId: item.regionId,
        regionName: item.regionName || '',
        address: item.address || '',
        latitude: item.latitude || 0,
        longitude: item.longitude || 0,
        totalBuildings: item.totalBuildings || 0,
        totalUnits: item.totalUnits || 0,
        totalHouseholds: item.totalHouseholds || 0,
        totalResidents: item.totalResidents || 0,
        occupancyRate: item.occupancyRate || 0,
        contactPhone: item.contactPhone || '',
        managerName: item.managerName || '',
        status: item.status,
        remark: item.remark || '',
        createTime: item.createTime,
        updateTime: item.updateTime
      }))
      
      console.log('转换后的社区列表:', communityList.value)
    } else {
      ElMessage.error(response.message || '加载社区列表失败')
    }
  } catch (error) {
    ElMessage.error('加载社区列表失败')
    console.error('加载社区列表失败:', error)
  }
}


const handleSearch = () => {
  pagination.current = 1
  loadShopList()
}

const handleReset = () => {
  Object.assign(searchForm, {
    communityId: undefined,
    shopType: undefined,
    shopName: '',
    shopCode: '',
    roomNumber: '',
    contactPerson: '',
    contactPhone: '',
    status: undefined,
    minArea: undefined,
    maxArea: undefined,
    minRentPrice: undefined,
    maxRentPrice: undefined
  })
  handleSearch()
}

const handleAdd = () => {
  selectedShopId.value = null
  formMode.value = 'add'
  formDialogVisible.value = true
}

const handleEdit = (row: ShopVO) => {
  selectedShopId.value = row.id
  formMode.value = 'edit'
  formDialogVisible.value = true
}

const handleView = (row: ShopVO) => {
  selectedShopId.value = row.id
  detailDialogVisible.value = true
}

const handleDelete = async (row: ShopVO) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除店铺"${row.shopName}"吗？删除后不可恢复！`, 
      '删除确认', 
      {
        type: 'warning',
        confirmButtonText: '确定删除',
        cancelButtonText: '取消'
      }
    )
    
    loading.value = true
    const response = await shopApi.deleteShop(row.id)
    
    if (response.code === 200) {
      ElMessage.success('删除成功')
      loadShopList()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
      console.error('删除失败:', error)
    }
  } finally {
    loading.value = false
  }
}

const handleExport = () => {
  ElMessage.info('导出功能开发中...')
}

const handleRefresh = () => {
  loadShopList()
}

const handleSelectionChange = (selection: ShopVO[]) => {
  selectedRows.value = selection
}

const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.current = 1
  loadShopList()
}

const handleCurrentChange = (current: number) => {
  pagination.current = current
  loadShopList()
}

const handleFormSuccess = () => {
  formDialogVisible.value = false
  loadShopList()
  ElMessage.success(formMode.value === 'add' ? '新增成功' : '编辑成功')
}

const handleFormCancel = () => {
  formDialogVisible.value = false
}

// 工具方法
const getShopTypeTagType = (shopType: number): 'success' | 'primary' | 'warning' | 'info' | 'danger' => {
  const typeMap: Record<number, 'success' | 'primary' | 'warning' | 'info' | 'danger'> = {
    1: 'success', // 餐饮
    2: 'primary', // 零售
    3: 'warning', // 服务
    4: 'info'     // 其他
  }
  return typeMap[shopType] || 'info'
}

const formatDateTime = (dateTime: string) => {
  return new Date(dateTime).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}
</script>

<style scoped>
.shop-management {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.search-area {
  margin-bottom: 20px;
}

.search-form {
  margin: 0;
}

.operation-area {
  margin-bottom: 20px;
}

.operation-buttons {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
  justify-content: flex-start;
  align-items: center;
}

.operation-buttons .el-button {
  margin: 0;
  padding: 4px 8px;
  font-size: 12px;
}

.table-area {
  margin-bottom: 20px;
}

.pagination-area {
  display: flex;
  justify-content: center;
}

.money-text {
  color: #f56c6c;
  font-weight: 600;
}

:deep(.el-card__body) {
  padding: 16px;
}

:deep(.el-table) {
  font-size: 14px;
}

:deep(.el-table .el-table__header) {
  background-color: #f5f7fa;
}

:deep(.el-table .el-table__row:hover) {
  background-color: #f5f7fa;
}

.shop-image-thumbnail {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 40px;
}

.no-image {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #c0c4cc;
  font-size: 12px;
  height: 40px;
}

.no-image .el-icon {
  font-size: 16px;
  margin-bottom: 2px;
}

.no-image span {
  font-size: 10px;
}
</style>
